<template>
  <div class="auth-container">
    <el-page-header @back="goBack" content="实名认证" class="page-header"></el-page-header>
    <el-form :model="authForm" :rules="rules" ref="authFormRef" label-position="top" class="auth-form">
      <el-form-item label="真实姓名" prop="name">
        <el-input v-model="authForm.name" placeholder="请输入您的真实姓名"></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="id_number">
        <el-input v-model="authForm.id_number" placeholder="请输入您的身份证号"></el-input>
      </el-form-item>
      <el-form-item label="身份证正面" prop="image_front">
        <el-upload
          :auto-upload="false"
          :on-change="handleFrontChange"
          :show-file-list="false"
          accept="image/*"
          action="#"
          class="uploader"
        >
          <img v-if="authForm.image_front_url" :src="authForm.image_front_url" class="id-card-image">
          <el-icon v-else class="uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="身份证反面" prop="image_back">
        <el-upload
          :auto-upload="false"
          :on-change="handleBackChange"
          :show-file-list="false"
          accept="image/*"
          action="#"
          class="uploader"
        >
          <img v-if="authForm.image_back_url" :src="authForm.image_back_url" class="id-card-image">
          <el-icon v-else class="uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="loading" class="submit-btn">提交认证</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const authFormRef = ref(null)
const loading = ref(false)

const authForm = reactive({
  name: '',
  id_number: '',
  image_front: null,
  image_back: null,
  image_front_url: '',
  image_back_url: ''
})

const rules = reactive({
  name: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  id_number: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '身份证号格式不正确',
      trigger: 'blur'
    }
  ],
  image_front: [{ required: true, message: '请上传身份证正面照片' }],
  image_back: [{ required: true, message: '请上传身份证反面照片' }]
})

const handleFrontChange = (file) => {
  authForm.image_front = file.raw
  authForm.image_front_url = URL.createObjectURL(file.raw)
}

const handleBackChange = (file) => {
  authForm.image_back = file.raw
  authForm.image_back_url = URL.createObjectURL(file.raw)
}

const goBack = () => {
  router.back()
}

const submitForm = () => {
  authFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      const formData = new FormData()
      formData.append('name', authForm.name)
      formData.append('id_number', authForm.id_number)
      formData.append('image_front', authForm.image_front)
      formData.append('image_back', authForm.image_back)

      try {
        const response = await request.post('/user/realname_auth/', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

        if (response.code === 200 || response.code === 202) {
          ElMessage.success('实名认证以提交处理！')
          userStore.isRealName = true
          setTimeout(() => {
            router.push({ path: '/user' })
          }, 3000)
        } else {
          ElMessage.error(response.msg || '认证失败，请稍后再试')
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || '请求失败，请检查网络或联系管理员')
      } finally {
        loading.value = false
      }
    } else {
      ElMessage.error('请完整填写表单')
    }
  })
}
</script>

<style scoped>
.auth-container {
  padding: 16px;
  background-color: #fff;
  min-height: 100vh;
}
.page-header {
  margin-bottom: 24px;
}
.auth-form {
  max-width: 500px;
  margin: 0 auto;
}
.uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: .2s;
}
.uploader .el-upload:hover {
  border-color: #409eff;
}
.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.id-card-image {
  width: 178px;
  height: 178px;
  display: block;
}
.submit-btn {
  width: 100%;
}
</style> 